package com.rookieci.totp.db;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * Created by 磁磁帅 on 2025/8/10
 * 功能：用于数据库操作的锁
 */
public class MyDBLock {
    private static MyDBLock myDBLook;

    public static MyDBLock getInstance() {
        if (myDBLook == null) {
            synchronized (MyDBLock.class) {
                if (myDBLook == null) myDBLook = new MyDBLock();
            }
        }
        return myDBLook;
    }

    private MyDBLock() {
        readWriteLock = new ReentrantReadWriteLock();
    }

    private final ReentrantReadWriteLock readWriteLock;

    /**
     * @return writeLock仅用于解锁操作(不需要writeLock.lock)
     */
    public ReentrantReadWriteLock.WriteLock writeLock() {
        ReentrantReadWriteLock.WriteLock writeLock = readWriteLock.writeLock();
        writeLock.lock();
        /*writeLock.unlock();*/
        return writeLock;
    }

    /**
     * 解锁
     *
     * @param writeLock 用于解锁，来自writeLock
     */
    public void unlock(ReentrantReadWriteLock.WriteLock writeLock) {
        if (writeLock == null) return;
        writeLock.unlock();
    }
}
